<?php
class QMSLData
{	
	public function __construct($p_strCountry)
	{
		$this->_country	= $p_strCountry;
		$this->_table	= strtolower($p_strCountry).'_msl_data';
	}
	
	function __destruct() 
	{

	}
		
	public function total()
	{
		$strQuery	= '
			SELECT COUNT(id) `total`
			FROM '.$this->_table;
		$db 		= Zend_Registry::get('db');
		$arrResult 	= $db->fetchAll($strQuery);
		$db->closeConnection();
		return isset($arrResult[0]['total']) ? $arrResult[0]['total'] : 0;
	}
	
	public function get_by_id($p_intId)
	{
		$strQuery		= 'SELECT * FROM '.$this->_table.' WHERE id='.intval($p_intId);
		$db 			= Zend_Registry::get('db');
		$resultValue	= $db->fetchAll($strQuery);
		$db->closeConnection();
		return $resultValue;
	}
	
	public function delete_by_weekday($p_strWeekday)
	{
		$strQuery		= 'DELETE FROM '.$this->_table.' WHERE weekday= "'. $p_strWeekday . '";';
		$db 			= Zend_Registry::get('db');
		$resultValue	= $db->execute($strQuery);
		$db->closeConnection();
		return $resultValue;
	}
	
	
	public function insert($p_arrParams)
	{
		$db	= Zend_Registry::get('db');
		$resultValue = $db->insert($this->_table, $p_arrParams);
		$db->closeConnection();
		return $resultValue;
	}
	
	public function update($p_arrParams, $p_intId)
	{
		$db	= Zend_Registry::get('db');
		$resultValue = $db->update($this->_table, $p_arrParams, 'id='.intval($p_intId));
		$db->closeConnection();
		return $resultValue;
	}
	
	public function reset()
	{
		$strQuery	= 'TRUNCATE '.$this->_table;
		$db 		= Zend_Registry::get('db');
		$db->execute($strQuery);
		$db->closeConnection();
	}
	
	public function getMSLDataFromGenerateForecasts()
	{
		$objForecasts = new QBForecast($this->_country);
		$arrDataMSL = $objForecasts->getForecastsData();
		
		$weekday = CConfig::getNextDay();	
		if($arrDataMSL)
		{
			$db 		= Zend_Registry::get('db');	
			$this->delete_by_weekday($weekday);
			
			foreach($arrDataMSL as $data)
			{
				$p_arrParams =array(
					'sku' => $data['sku'],
					'msl' =>  $data['msl'],
					'weekday' => $weekday,
					'created_at' => new Zend_Db_Expr('NOW()')
					);  
				$db->insert($this->_table, $p_arrParams);
			} 
			$db->closeConnection();
		}
	}
}
?>

